package tech.aistar.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import tech.aistar.entity.User;
import tech.aistar.entity.UserInfo;
import tech.aistar.entity.UserLogin;
import tech.aistar.service.IUserInfoService;
import tech.aistar.service.IUserLoginService;
import tech.aistar.service.IUserService;
import tech.aistar.util.SmsService;

import javax.security.auth.Subject;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author Ace
 * @version 1.0
 * @descriiption:本类用来演示:
 * @date 2019/9/27 0027.
 */
@Controller
@RequestMapping("/user")
public class UserController {

    //控制层调用service层
    @Autowired
    private IUserLoginService userLoginService;
    @Autowired
    private IUserInfoService userInfoService;
    /**
     * 转发到/login-register.jsp
     * @return
     */
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 退出
     * @param
     * @param
     * @return
     */
    @RequestMapping("/exit")
    public String exit(HttpServletRequest req){
        req.getSession().invalidate();
        return "login-register";
    }

    @GetMapping("/loginding")
    public String loginView(Model model, Integer error){
        if(error!=null){
            model.addAttribute("error",error);
        }
        return "login-register";
    }
    /**
     * 参数 - userId和userPassword
     *      - flag - 记住密码
     */
    @RequestMapping("/login")
    public String login(String uId, String pwd, String flag, HttpServletResponse resp, HttpServletRequest req){
        //1 - 接受的参数
        //2 - 跳转的目的地
        System.out.println(uId);
        System.out.println(pwd);
        //控制层 调用 service层,调用 mapper层
        UserLogin userLogin=userLoginService.findByUserId(uId);
        if (userLogin !=null){
            //用户是存在的
            if(passwordEncoder.matches(pwd,userLogin.getUserPassword())){
                //判断是否记住密码
                if (flag!=null){
                    //将用户账号和密码保存到cookie - 发送到客户端
                    String userId = userLogin.getUserId();
                    try {
                        userId = URLEncoder.encode(URLEncoder.encode(userId,"utf-8"),"utf-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    Cookie c = new Cookie("userLogin",userId+":"+pwd);
                    c.setPath("/");
                    //通过响应头信息将cookie返回给客户端
                    resp.addCookie(c);
                }else {
                    Cookie c =new Cookie("userLogin","");
                    c.setPath("/");
                    resp.addCookie(c);
                }
                //将登陆成功之后的userLogin对象放入到session作用域
                //一次会话期间
                req.getSession().setAttribute("user",userLogin);

                UserInfo info=userInfoService.findById(userLogin.getId());
                req.getSession().setAttribute("info",info);
                return "redirect:/info/index";
            }else {
                //密码错误
                return "redirect:loginding?error=1";
            }
        }else {
//            用户是不存在的
            return "redirect:loginding?error=0";
        }
//        return null;
    }

    @PostMapping("register")
    @ResponseBody
    public String register(HttpServletRequest req,String uId,String pwd1,String pwd2,String phoneNumber,String preauthcode){
        UserLogin userLogin=userLoginService.findByUserId(uId);
        System.out.println(userLogin);
        System.out.println(uId+"&"+pwd1+"&"+pwd2+"&"+preauthcode);
        //验证码校验
        HttpSession ss=req.getSession();
        String autocode= (String) ss.getAttribute("autocode");
        System.out.println(autocode);
        if (autocode==null){
            return "验证码错误";
        }else if (autocode.equals(preauthcode)){
            if(userLogin==null){
                System.out.println();
                if(pwd1!=null & pwd1.trim()!=""){
                    if(pwd1.equals(pwd2)){
                        UserLogin userLogin1=new UserLogin();
                        userLogin1.setUserId(uId);
                        userLogin1.setUserPassword(pwd1);
                        userLogin1.setUserStatus(0);
                        userLoginService.addUserLogin(userLogin1);
                        System.out.println(userLogin1.getId());
                        int id=userLogin1.getId();

                        userInfoService.addUserInfo(id,uId,null);
                        userInfoService.addPhone(phoneNumber,id);
                        return "ok";
                    }else {
                        return "两次密码不一致";
                    }
                }else {
                    return "请您输入密码";
                }
            }else {
                return "用户名已存在";
            }
        }else{
            return "验证码错误";
        }
    }
    /**
     * 后台获取验证码
     */
    @PostMapping("/getcode")
    @ResponseBody
    public String getcode(String phoneNumber,HttpServletRequest req){
        //随机生成六位随机数
        StringBuffer stringBuffer=new StringBuffer();
        for (int x=0;x<=5;x++) {
            int random = (int) (Math.random() * (10 - 1));
            stringBuffer.append(random);
        }
        String code = stringBuffer.toString();
        //session中保存我后台生成的code,为了将来拿出来与用户提交的进行比较。
        HttpSession session = req.getSession();
        session.setAttribute("autocode",code);
        if(phoneNumber==""){
                    return "发送失败";
        }else{
            //把后台生成的code和所发送的手机号传进发送消息类，调用执行。
            System.out.println(phoneNumber);
            SmsService.send(phoneNumber,code);
            return "已获取手机号并发送";
        }
    }
}